package ch02sl.sl.sl6;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class XMLParse {
    Document doc = null;
    public  void getDocument(){
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse("src/test/java/ch02sl/sl6/收藏信息.xml");
             NodeList list = doc.getElementsByTagName("Brand");
            for (int i = 0; i < list.getLength() ; i++) {
                Element brandElement = (Element) list.item(i);
                String brandName = brandElement.getAttribute("name");
                if (brandName.equals("SAMSUNG")){
                    brandElement.getParentNode().removeChild(brandElement);
                }
            }
            //保存xml文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);

            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            StreamResult result = new StreamResult(new FileOutputStream("src/test/java/ch02sl/sl6/收藏信息.xml"));
            transformer.transform(domSource,result);

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
    public  void showInfo() {
        NodeList nodeList = doc.getElementsByTagName("Brand");
        for (int i = 0; i <nodeList.getLength() ; i++) {
            Node brand = nodeList.item(i);
            Element brandEle = (Element) brand;
            String brandStr = brandEle.getAttribute("name");
            NodeList types = brandEle.getChildNodes();
            for (int j = 0; j <types.getLength() ; j++) {
                Node type  = types.item(j);
                if (type.getNodeType() == Node.ELEMENT_NODE){
                    Element typeELe = (Element) type;
                    String typeStr = typeELe.getAttribute("name");
                    System.out.println("手机："+brandStr+typeStr);
                }

            }
        }
    }

    public static void main(String[] args) {
        XMLParse parse = new XMLParse();
        parse.getDocument();
        parse.showInfo();
    }
}
